<?php
namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Closure;
use think\Request;
use think\Response;

class JwtAuth
{
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            return json(['code' => 401, 'msg' => 'Token 未提供']);
        }

        try {
            // 提取并解码 Token
            $decoded = JWT::decode($token, new Key(config('jwt.key'), 'HS256'));
            $decoded = (array)$decoded;

            // 检查是否记住我并验证数据库 Token
            if (!empty($decoded['remember'])) {
                $user = Db::name('user')
                    ->where('id', $decoded['uid'])
                    ->find();
                if (!$user || $user['remember_token'] !== $token) {
                    throw new \Exception('Token 无效');
                }
            }

            // 将用户信息附加到请求
            $request->user = $decoded;
        } catch (\Exception $e) {
            return json(['code' => 401, 'msg' => 'Token 无效或过期']);
        }

        return $next($request);
    }
}